package com.wxy.ej.flow.modules.taskflow.repository;

import com.wxy.ej.flow.modules.act.dto.UserDto;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;

/**
 * T2  Repository 接口
 * 数据仓库：主要处理数据的逻辑处理、缓存处理等相关功能，为service层提供更直观的数据服务
 * @author wuxiaoyong
 * @since 2022-01-16
 */

@Repository
public class JdbcRepository {

    @Resource
    JdbcTemplate jdbcTemplate;

    public List<UserDto> executeSql(String sql) {
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(UserDto.class));
    }


    public List<Map<String, Object>> executeQuery(String sql, List<Object> paramList) {
        // return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Map.class));
        return jdbcTemplate.queryForList(sql, paramList.toArray());
    }

    /**
     * update 返回成功记录数
     * @param sql
     * @param paramList
     * @return
     */
    public int executeUpdate(String sql, List<Object> paramList) {
        return jdbcTemplate.update(sql, paramList.toArray());
    }

    /**
     * insert 返回主键
     * @param sql
     * @param paramList
     * @return
     */
    public int executeInsert(String sql, List<Object> paramList) {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator(){
                                @Override
                                public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
                                    PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                                    int i=1;
                                    for (Object paramObj:paramList) {
                                        ps.setObject(i++, paramObj);
                                    }
                                    return ps;
                                }
                            },
                keyHolder);

        return keyHolder.getKey().intValue();
    }

}
